package hlhj.fhp.supreme.activitys

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v7.app.AlertDialog
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import fhp.hlhj.giantfold.utils.LogUtil
import hlhj.fhp.supreme.BaseAty
import hlhj.fhp.supreme.R
import hlhj.fhp.supreme.javabean.BaseBean
import hlhj.fhp.supreme.javabean.CartBean
import hlhj.fhp.supreme.network.Urls
import hlhj.fhp.supreme.utils.JsonCallBack
import hlhj.fhp.supreme.utils.MyUtils
import kotlinx.android.synthetic.main.activity_cart_aty.*
import kotlinx.android.synthetic.main.lo_cont.*

class CartAty : BaseAty() {
    private var type="0"
    private var isEdit=false
    private var isAll=false
    private val cartDatas=ArrayList<CartBean.DataBean>()
    private val chooseHash=HashMap<Int,Boolean>()
    private val chooseNumHash=HashMap<Int,Int>()
    private val GOCONFIRM=1
    private lateinit var cartAdp:BaseQuickAdapter<CartBean.DataBean,BaseViewHolder>

    override fun getContentId(): Int {
        return R.layout.activity_cart_aty
    }

    override fun initView() {
        setAdp()

        recyclerview.layoutManager=LinearLayoutManager(this,LinearLayout.VERTICAL,false)
        recyclerview.adapter=cartAdp


        getData()
    }

    private fun setAdp() {
        cartAdp = object : BaseQuickAdapter<CartBean.DataBean, BaseViewHolder>(R.layout.cart_item, cartDatas) {
            override fun convert(helper: BaseViewHolder?, item: CartBean.DataBean?) {
                Glide.with(mContext).load(item?.img).asBitmap().dontAnimate().into(helper?.getView(R.id.itemIcon))
                helper?.setText(R.id.itemTittle, item?.title)
                when (type) {
                    "0" -> {
                        helper?.setText(R.id.itemPrice, "￥" + item?.money)
                    }
                    "1" -> {
                        helper?.setText(R.id.itemPrice, item?.score + "积分")
                    }
                }
                LogUtil.log("选择表${chooseHash.toString()}数量表${chooseNumHash.toString()}")
                if (chooseHash[helper?.adapterPosition]!!) {
                    helper?.setImageResource(R.id.imgCheck, R.mipmap.ic_sure)
                } else {
                    helper?.setImageResource(R.id.imgCheck, R.mipmap.ic_sure_grey)
                }


                val btCut = helper?.getView<TextView>(R.id.btCut)
                val btAdd = helper?.getView<TextView>(R.id.btAdd)
                val tvNum = helper?.getView<TextView>(R.id.tvNum)

                tvNum?.text = chooseNumHash[helper?.adapterPosition].toString()

                btCut?.setOnClickListener {
                    if (tvNum?.text.toString().toInt() > 1) {
                        OkGo.post<BaseBean>(Urls.BaseUrl + Urls.EDIT_NUM)
                                .params("id", item?.id!!)
                                .params("number", (chooseNumHash[helper?.adapterPosition]!! - 1))
                                .execute(object : JsonCallBack<BaseBean>(this@CartAty) {
                                    override fun onSuccess(response: Response<BaseBean>?) {
                                        val bean = response?.body()
                                        if (bean?.code == 1) {
                                            chooseNumHash.put(helper?.adapterPosition, (tvNum?.text.toString().toInt() - 1))
                                            notifyDataSetChanged()
                                            changePrice()
                                        } else {
                                            MyUtils.toast(bean?.msg)
                                        }
                                    }
                                })
    //                        tvNum?.text=(tvNum?.text.toString().toInt()-1).toString()
                    }
                }

                btAdd?.setOnClickListener {
                    OkGo.post<BaseBean>(Urls.BaseUrl + Urls.EDIT_NUM)
                            .params("id", item?.id!!)
                            .params("number", (chooseNumHash[helper?.adapterPosition]!! + 1))
                            .execute(object : JsonCallBack<BaseBean>(this@CartAty) {
                                override fun onSuccess(response: Response<BaseBean>?) {
                                    val bean = response?.body()
                                    if (bean?.code == 1) {
                                        chooseNumHash.put(helper?.adapterPosition, (tvNum?.text.toString().toInt() + 1))
                                        notifyDataSetChanged()
                                        changePrice()
                                    } else {
                                        MyUtils.toast(bean?.msg)
                                    }
                                }
                            })
    //                        tvNum?.text=(tvNum?.text.toString().toInt()+1).toString()

                }

            }
        }
    }


    override fun initListener() {
        btExit.setOnClickListener {
            finish()
        }
        btCommit.setOnClickListener {
            val selectDatas=ArrayList<CartBean.DataBean>()
            for (i in 0..chooseHash.size-1){
                if (chooseHash[i]!!){
                    val dataBean = cartDatas[i]
                    dataBean.number=chooseNumHash[i]!!
                    selectDatas.add(dataBean)
                }
            }
            if (selectDatas.size>=1){
                val intent = Intent(this, ConfirmOrderAty::class.java)
                intent.putExtra("datas",selectDatas)
                intent.putExtra("et","2")
                intent.putExtra("totalMoney",tvTotalPrice.text.toString())
                intent.putExtra("type",type)
                startActivity(intent)
            }else{
                MyUtils.toast("请选择商品")
            }
        }
        btExit.setOnClickListener {
            finish()
        }
        btManner.setOnClickListener {
            if(!isEdit){
                isEdit=true
                loEdit.visibility=View.VISIBLE
            }else{
                isEdit=false
                loEdit.visibility=View.GONE
            }
        }
        tvEdit.setOnClickListener {
            if (!isAll){
                isAll=true
                val weather = resources.getDrawable(R.mipmap.ic_sure)
                weather.setBounds(0, 0, weather.getMinimumWidth(), weather.getMinimumWidth());
                tvEdit.setCompoundDrawables(weather, null, null, null);
                for (i in 0..chooseHash.size-1){
                    chooseHash.put(i,true)
                    cartAdp.notifyDataSetChanged()
                    changePrice()
                }
            }else{
                isAll=false
                val weather = resources.getDrawable(R.mipmap.ic_sure_grey)
                weather.setBounds(0, 0, weather.getMinimumWidth(), weather.getMinimumWidth());
                tvEdit.setCompoundDrawables(weather, null, null, null);
                for (i in 0..chooseHash.size-1){
                    chooseHash.put(i,false)
                    cartAdp.notifyDataSetChanged()
                    changePrice()

                }
            }
        }
        btDelet.setOnClickListener {
            var isFirst=true

            AlertDialog.Builder(this)
                    .setTitle("确定删除？")
                    .setPositiveButton("确定"){
                        dialog, which ->
                        var str=""
                        for (i in 0..chooseHash.size-1){
                            if (chooseHash[i]!!){
                                if (isFirst){
                                    isFirst=false
                                    str=str+cartDatas[i].id
                                }else{
                                    str=str+","+cartDatas[i].id
                                }
                            }
                        }
                        OkGo.post<BaseBean>(Urls.BaseUrl+Urls.CART_DELET)
                                .params("ids",str)
                                .execute(object :JsonCallBack<BaseBean>(this@CartAty){
                                    override fun onSuccess(response: Response<BaseBean>?) {
                                        val bean = response?.body()
                                        if (bean?.code==1){
                                            MyUtils.toast(bean?.msg)
                                            cartDatas.clear()
                                            getData()
                                        }
                                    }
                                })
                    }
                    .setNegativeButton("取消"){
                        dialog, which ->
                        dialog.dismiss()
                    }

                    .show()

        }

        cartAdp.setOnItemClickListener { adapter, view, position ->
            for ( i in 0..chooseHash.size-1){
                if (i==position){
                    if (chooseHash[i]!!){
                        chooseHash.put(i,false)
                    }else{
                        chooseHash.put(i,true)
                    }
                }else{
                }
            }
            changePrice()
            cartAdp.notifyDataSetChanged()
        }
        tabLayout.addOnTabSelectedListener(object :TabLayout.OnTabSelectedListener{
            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabSelected(tab: TabLayout.Tab?) {
                when(tab?.position){
                    0->{
                        cartDatas.clear()
                        type="0"
                        getData()
                        tvTotalPrice.text="0"
                    }
                    1->{
                        cartDatas.clear()
                        type="1"
                        getData()
                        tvTotalPrice.text="0"
                    }
                }
            }
        })
    }
    private fun getData() {
        OkGo.post<CartBean>(Urls.BaseUrl+Urls.CART)
                .params("type",type)
                .execute(object :JsonCallBack<CartBean>(this){
                    override fun onSuccess(response: Response<CartBean>?) {
                        val bean = response?.body()
                        if (bean?.code==1){
                            chooseHash.clear()
                            chooseNumHash.clear()
                            if (bean?.data!=null){
                                cartDatas.addAll(bean?.data)
                                bean?.data.forEachIndexed { index, dataBean ->
                                    chooseHash.put(index,false)
                                    chooseNumHash.put(index,bean?.data[index].number)
                                }
                            }
                            cartAdp.notifyDataSetChanged()
                        }
                    }
                })
    }

    fun changePrice(){
        var totalPrice=0.0
        var totalPoint=0
        for (i in 0..chooseHash.size-1){
            if (chooseHash[i]!!){
                totalPrice=(cartDatas[i].money.toDouble()*chooseNumHash[i]!!)+totalPrice
                totalPoint=(cartDatas[i].score.toInt()*chooseNumHash[i]!!)+totalPoint
            }
        }
        if (type.equals("0")){
            tvTotalPrice.text="￥$totalPrice"
        }else{
            tvTotalPrice.text="${totalPoint}积分"
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode!=-1)return
        when(requestCode){
            1->{
                finish()
            }
        }
    }
    interface OnPriceChangeListener{
        fun priceChanged()
    }
}
